/****************************************************
	文件：MediatorPattern.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/5/5 22:47:52
	功能：中介者模式
*****************************************************/

using System.Collections.Generic;
using UnityEngine;

namespace DesignPatterns
{
    public class MediatorPattern : MonoBehaviour
    {
        private void Start()
        {
            //中介者模式：此例子写的稍有问题，以后改善
            MediatorA mediatorA = new MediatorA();
            mediatorA.Add("PlayerModel", new PlayerModel());
            mediatorA.Add("PlayerView", new PlayerView());
            mediatorA.Add("MainView", new MainView());
            mediatorA.SendMsg("PlayerModel", "玩家数据 xxx 发生变动.");
        }

        /// <summary>
        /// 中介者基类
        /// </summary>
        public abstract class MediatorBase
        {
            /// <summary>
            /// 中介者内部的成员列表
            /// </summary>
            protected Dictionary<string, IMember> mMemberDict;
            public MediatorBase()
            {
                mMemberDict = new Dictionary<string, IMember>();
            }
            public void Add(string name, IMember member)
            {
                if(mMemberDict.ContainsKey(name))
                    mMemberDict[name] = member;
                else
                    mMemberDict.Add(name, member);
            }
            public void Remove(string name)
            {
                mMemberDict.Remove(name);
            }
            public void SendMsg<T>(string fromName, T msg)
            {
                if (mMemberDict.ContainsKey(fromName) == false) return;
                foreach (var pair in mMemberDict)
                {
                    if (pair.Key == fromName) continue;
                    pair.Value.ReceiveMsg(msg);
                }
            }
        }
        public class MediatorA:MediatorBase
        {
        }
        /// <summary>
        /// 中介者内部成员的成员接口
        /// </summary>
        public interface IMember
        {
            void ReceiveMsg<T>(T msg);
        }
        public class PlayerModel : IMember
        {
            public void ReceiveMsg<T>(T msg)
            {
                Debug.Log("PlayerModel 收到消息：" + msg.ToString());
            }
        }
        public class PlayerView : IMember
        {
            public void ReceiveMsg<T>(T msg)
            {
                Debug.Log("PlayerView 收到消息：" + msg.ToString());
            }
        }
        public class MainView : IMember
        {
            public void ReceiveMsg<T>(T msg)
            {
                Debug.Log("MainView 收到消息：" + msg.ToString());
            }
        }
    }
}
